﻿using System;
using System.Linq;
using System.Collections.Generic;
using PharmacyPharnet.Core;
using Pharmacy.Data;
using Pharmacy.Data.Entity;
using Pharmacy.Business;
using Pharmacy.Ultilities;
using Pharmacy.Ultilities.Resources;
using System.Windows.Forms;
using Pharmacy.ExceptionHandling;
using System.Data;

namespace PharmacyPharnet.KinhDoanh
{
    public partial class FrmPhieuDatHang : FrmListBaseWithSearch
    {
        #region Declarations
        Repository<PhieuDatHang> rPhieuDatHang;
        IObjectContext pharmacyContext;
        PhieuDatHangBO pdhBO;
        #endregion

        #region Constructors
        public FrmPhieuDatHang()
        {
            InitializeComponent();
            this.PersistentType = typeof(PhieuDatHang).Name;
            pharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);            
        }        
        #endregion

        #region Override Methods
        protected override void PopulateData()
        {
            BindData();
        }

        protected override void InitializeBO()
        {
            if (pharmacyContext == null)
                pharmacyContext = ObjectContextFactory.CreatePharmacyContext(Global.UserName, Global.CurrentConnectionString);
            if (pdhBO == null)
                pdhBO = new PhieuDatHangBO(pharmacyContext);

        }
        #endregion

        #region Custom Methods
        private void BindData()
        {
            rPhieuDatHang = pdhBO.ListPhieuDatHang();
            List<PhieuDatHang> lst = null;
            DateTime fromDate, toDate;
            if (dteFromDate.Text != string.Empty && dteToDate.Text != string.Empty)
            {
                fromDate = DateTime.Parse(dteFromDate.EditValue.ToString());
                toDate = DateTime.Parse(dteToDate.EditValue.ToString());
                lst = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate >= fromDate && pdh.DocumentDate <= toDate && pdh.Status == (int)Enums.PhieuDatHangStatus.New)
                                .ToList();
            }
            else if (dteFromDate.Text != string.Empty && dteToDate.Text == string.Empty)
            {
                fromDate = DateTime.Parse(dteFromDate.EditValue.ToString());
                lst = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate >= fromDate && pdh.Status == (int)Enums.PhieuDatHangStatus.New)
                                .ToList();
            }
            else if (dteFromDate.Text == string.Empty && dteToDate.Text != string.Empty)
            {
                toDate = DateTime.Parse(dteToDate.EditValue.ToString());
                lst = rPhieuDatHang.AsQueryable()
                                .Where(pdh => pdh.DocumentDate <= toDate && pdh.Status == (int)Enums.PhieuDatHangStatus.New)
                                .ToList();
            }
            else
            {
                lst = rPhieuDatHang.AsQueryable().Where(pdh => pdh.Status == (int)Enums.PhieuDatHangStatus.New).ToList();
            }
            grdMasterData.DataSource = null;
            this.grdMasterData.DataSource = lst;
            grvMasterData.BestFitColumns();
        }

        private void RegisterEventhandler()
        {
            btnDelete.Click += new EventHandler(btnDelete_Click);
            btnEdit.Click += new EventHandler(btnEdit_Click);
            //
            //btnNew
            //
            this.btnNew.Click += new EventHandler(btnNew_Click);

            //
            //btnReloadData
            //
            this.btnReloadData.Click += new EventHandler(btnReloadData_Click);
            
            //
            // Filter data
            //
            this.FilterSubmit += new OnFilterEventHandler(FrmPhieuDatHang_FilterSubmit);

        }
        #endregion

        #region Event Handlers
        void FrmPhieuDatHang_FilterSubmit(object sender, EventArgs e)
        {
            try
            {
                ViewManager.CreateWaitDialog();
                ViewManager.SetWaitDialogCaption(SR.Instance.GetString(Constant.ENT_MASTERITEM), "Reloading...");
                BindData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
            finally
            {
                ViewManager.CloseWaitDialog();
            } 
        }

        void btnReloadData_Click(object sender, System.EventArgs e)
        {
            try
            {
                ViewManager.CreateWaitDialog();
                ViewManager.SetWaitDialogCaption(SR.Instance.GetString(Constant.ENT_MASTERITEM), "Reloading...");
                BindData();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
            finally
            {
                ViewManager.CloseWaitDialog();
            }
        }

        void btnNew_Click(object sender, System.EventArgs e)
        {
            try
            {
                FrmPhieuDatHangChiTiet frm = new FrmPhieuDatHangChiTiet(Enums.ActionForm.New);
                frm.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                Close();
            }

            //ViewManager.ShowView(frm);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            int focusRow = grvMasterData.FocusedRowHandle;
            PhieuDatHang currentObject = grvMasterData.GetRow(focusRow) as PhieuDatHang;
            try
            {
                if (grvMasterData.DataSource != null)
                {
                    pdhBO.LockPhieuDatHang(currentObject, out msg);
                    if (msg.Length > 0)
                    {
                        MessageBox.Show(msg);
                        return;
                    }
                    FrmPhieuDatHangChiTiet frm = new FrmPhieuDatHangChiTiet(pharmacyContext, currentObject, Enums.ActionForm.Edit);
                    frm.ShowDialog();
                }
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                pdhBO.UnLockPhieuDatHang(currentObject, out msg);
                if (msg.Length > 0)
                {
                    MessageBox.Show(msg);
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (grvMasterData.DataSource != null)
                {
                    int focusRow = grvMasterData.FocusedRowHandle;
                    PhieuDatHang currentObject = grvMasterData.GetRow(focusRow) as PhieuDatHang;
                    string messageError = string.Empty;
                    bool result = pdhBO.DeletePhieuDatHang(currentObject.ID, out messageError);
                    if (result)
                        btnReloadData.PerformClick();
                    else
                        MessageBox.Show(messageError);
                }
            }
            catch (UpdateException exc)
            {
                ExceptionHandler.LogWriter.Write(exc.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(Pharmacy.Ultilities.Resources.SR.Instance.GetString(Constant.KEY_DELETEOBJECTINTRANSACTION));
            }
            catch (Exception ex)
            {

                ExceptionHandler.LogWriter.Write(ex.Message, ExceptionHandler.LOG_CAT_GENERAL);
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        private void FrmPhieuDatHang_Load(object sender, EventArgs e)
        {
            try
            {
                RegisterEventhandler();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Có lỗi xảy ra. Vui lòng liên hệ Người quản trị hệ thống để được hỗ trợ.");
                ExceptionHandler.LogWriter.Write(ex, ExceptionHandler.LOG_CAT_GENERAL);
                this.Close();
            }
            finally
            {
                ViewManager.CloseWaitDialog();
            }
        }
        
    }
}